package org.xacmlauth.util;

import java.io.InputStream;
import java.io.StringReader;

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.xml.sax.SAXException;

public class SchemaValidator {
	
//	private static final Log LOG = LogFactory.getLog(SchemaValidator.class);
	
	public static boolean isValidRequest(String request, String xsdFileName) throws Exception{
		boolean isValid = false;
		
		InputStream xsdStream = SchemaValidator.class.getClassLoader().getResourceAsStream(xsdFileName);
		Source xsdSource = new StreamSource(xsdStream);
		
		Source xmlContent = new StreamSource(new StringReader(request));
		SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
		Schema schema = schemaFactory.newSchema(xsdSource);
	
		Validator validator = schema.newValidator();
		try {
		  validator.validate(xmlContent);
		  isValid = true;
		} catch (SAXException e) {
//			LOG.error("Schema validation error ", e);
		}

		
		return isValid;
	}

}
